# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "net/http"
require 'json'

# This example filter will replace the contents of the default
# message field with whatever you specify in the configuration.
#
# It is only intended to be used as an example.
class LogStash::Filters::Restful < LogStash::Filters::Base

  # Setting the config_name here is required. This is how you
  # configure this filter from your Logstash config.
  #
  # filter {
  #   example {
  #     message => "My message..."
  #   }
  # }
  #
  config_name "restful"

  # 获得Restful信息的网址，包括端口
  config :uri, :validate => :string, :required => true, :default => "http://localhost:53833/ipi/"


  # 这个字段中包含传送给Restful接口的参数值，整个网址为 :url + 这个值。
  # 换句话说，此过滤器只接受一个参数
  # this field is an array, only the first value will be used.
  config :source, :validate => :string, :required => true

  # 改变Restful返回值存储的字段名,默认值为restfulData
  config :target, :validate => :string, :default => 'restfulData'


  public
  def register
    # Add instance variables
  end # def register

public
def filter(event)
   return unless filter?(event)
   return unless not @uri.strip.blank?
   begin
      param = event.[](@source)
      return unless not param.strip.blank?
      url = @uri + param
      rest_hash = getRestful(url)
      if event.include?(@target) then
         old = event.[](@target)
         ret_array = []
         if old.class == Array then
           ret_array.concat(old)
         else
           ret_array << old
         end
         ret_array << rest_hash
         event.[]=(@target, ret_array)
      else
         event.[]=(@target, rest_hash)
      end  
   rescue Exception => e
      event.[]=(@target, {})
      @logger.error('unknown erroe while looking up restful data', :exception => e, :field => @source, :event => event)
   end 
   # filter_matched should go in the last line of our successful code
   filter_matched(event)
end # def filter


private
  def getRestful(url)
    rstr = Net::HTTP.get(URI.parse(url))
    rhash = JSON.parse(rstr)
    return rhash
  end
end # class LogStash::Filters::Example
